package com.tianji.learning.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.tianji.api.client.course.CourseClient;
import com.tianji.api.dto.course.CourseFullInfoDTO;
import com.tianji.api.dto.leanring.LearningLessonDTO;
import com.tianji.api.dto.leanring.LearningRecordDTO;
import com.tianji.api.dto.leanring.LearningRecordFormDTO;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.po.LearningLesson;
import com.tianji.learning.domain.po.LearningRecord;
import com.tianji.learning.enums.LessonStatus;
import com.tianji.learning.enums.SectionType;
import com.tianji.learning.mapper.LearningRecordMapper;
import com.tianji.learning.service.ILearningLessonService;
import com.tianji.learning.service.ILearningRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 学习记录表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-6-25
 */
@Service
public class LearningRecordServiceImpl extends ServiceImpl<LearningRecordMapper, LearningRecord> implements ILearningRecordService {

    @Resource
    private ILearningLessonService iLearningLessonService;

    @Resource
    private CourseClient courseClient;

    @Override
    public LearningLessonDTO queryLearningRecordByCourse(Long courseId) {
        Long user = UserContext.getUser();

        //查询课表信息  条件userId courseId
        LearningLesson lesson = iLearningLessonService.lambdaQuery()
                .eq(LearningLesson::getUserId, user)
                .eq(LearningLesson::getCourseId, courseId)
                .one();

        if (lesson == null) {
            throw new BizIllegalException("该课程未加入课表");
        }
        //查询学习记录  条件userId userId
        List<LearningRecord> recordList = lambdaQuery()
                .eq(LearningRecord::getUserId, user)
                .eq(LearningRecord::getLessonId, lesson.getId())
                .list();
        //封装结果返回
        LearningLessonDTO learningLessonDTO = new LearningLessonDTO();
        learningLessonDTO.setId(lesson.getId());
        learningLessonDTO.setLatestSectionId(lesson.getLatestSectionId());

        learningLessonDTO.setRecords(BeanUtils.copyList(recordList, LearningRecordDTO.class));
        return learningLessonDTO;
    }

    @Override
    public void addLearningRecord(LearningRecordFormDTO formDTO) {
        Long user = UserContext.getUser();

        //2.处理学习记录
        Boolean isFinshed = false;
        if (formDTO.getSectionType().equals(SectionType.VIDEO)) {
            //2.1提交视频播放记录
            isFinshed = handleVideoRecord(user,formDTO);
        }else {
            //2.1提交考试记录
            isFinshed = handleExamRecord(user,formDTO);
        }
        //3.处理课表数据
        handleLessonDate(formDTO,isFinshed);
    }

    private void handleLessonDate(LearningRecordFormDTO formDTO, Boolean isFinished) {
        LearningLesson lesson = iLearningLessonService.getById(formDTO.getLessonId());
        if (lesson == null) {
            throw new BizIllegalException("GG");
        }
        boolean allFinished = false;
        //判断是否第一次学完 isFinished=true
        if (isFinished) {
            //调用课程服务 得到课程信息
            CourseFullInfoDTO cinfo = courseClient.getCourseInfoById(lesson.getCourseId(), false, false);
            Integer sectionNum = cinfo.getSectionNum();//得到该课程下小节总数

           allFinished  = lesson.getLearnedSections() + 1 >= sectionNum; //判断是否所有小节是否已经徐万
        }
        //更新课表数据
        iLearningLessonService.lambdaUpdate()
                .set(allFinished,LearningLesson::getStatus, LessonStatus.FINISHED)
                .set(lesson.getStatus()==LessonStatus.NOT_BEGIN,LearningLesson::getStatus, LessonStatus.LEARNING)
                .set(LearningLesson::getLatestSectionId, lesson.getLatestSectionId())
                .set(LearningLesson::getLatestLearnTime, lesson.getLatestLearnTime())
//                .set(isFinished,LearningLesson::getLearnedSections, lesson.getLearnedSections()+1)  //存在线程安全问题
                .setSql(isFinished,"learned_sections = learned_sections+1")
                .eq(LearningLesson::getId, lesson.getId())
                .update();

        }

    private Boolean handleVideoRecord(Long user, LearningRecordFormDTO formDTO) {
        LearningRecord learningrecord = lambdaQuery()
                .eq(LearningRecord::getUserId, user)
                .eq(LearningRecord::getLessonId, formDTO.getLessonId())
                .eq(LearningRecord::getSectionId, formDTO.getSectionId())
                .one();
        if (learningrecord == null) {
            LearningRecord record = new LearningRecord();
            BeanUtils.copyProperties(formDTO,record);
            record.setUserId(user);
            boolean save = save(record);
            if (!save) {

            }
            return  false;//代表本小节没有学完
        }
            //更新学习记录
            // isFinished为true代表第一次学完
            boolean isFinished = !learningrecord.getFinished() && formDTO.getMoment() * 2 >= formDTO.getDuration();
            boolean update = lambdaUpdate()
                    .set(LearningRecord::getMoment, formDTO.getMoment())
                    .set(isFinished, LearningRecord::getFinished, true)
                    .set(isFinished, LearningRecord::getFinishTime, formDTO.getCommitTime())
                    .eq(LearningRecord::getId, learningrecord.getId())
                    .update();
            if (!update) {

            }
        return isFinished;

    }

    private Boolean handleExamRecord(Long user, LearningRecordFormDTO formDTO) {
        LearningRecord record = new LearningRecord();
        BeanUtils.copyProperties(formDTO,record);
        record.setUserId(user);
        record.setFinished(true);
        record.setFinishTime(formDTO.getCommitTime());

        boolean save = save(record);
        if (!save) {

        }
        return true;
    }
}
